package com.stock_t.controller;

import com.stock_t.dto.ApiResponse;
import com.stock_t.utils.EastMoneyFundFlowUtil;
import com.stock_t.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

/**
 * - 股票实时数据控制器
 * - 提供股票实时行情数据的REST API接口
 */
@RestController
@RequestMapping("/api/realtime")
public class StockRealTimeController {

    @Autowired
    private RedisCache redisCache;

    /**
     * - 获取股票实时行情数据
     * -
     * - @param stockCode 股票代码
     * - @return 包含收盘价的响应对象
     */
    @GetMapping("/quote/{stockCode}")
    public ApiResponse<Map<String, Object>> getRealTimeQuote(@PathVariable String stockCode) {
        String cacheKey = "stock:quote:" + stockCode;
        
        // 判断是否需要使用缓存，添加异常处理
        if (shouldUseCache()) {
            try {
                Map<String, Object> cachedData = redisCache.getCacheObject(cacheKey);
                if (cachedData != null) {
                    return ApiResponse.success("获取实时行情成功(缓存)", cachedData);
                }
            } catch (Exception e) {
                // Redis异常时，忽略缓存，直接获取实时数据
                System.err.println("Redis缓存异常，使用实时数据: " + e.getMessage());
            }
        }
        
        try {
            Map<String, Object> originalResult = EastMoneyFundFlowUtil.fetchZhengDiefu(stockCode);
            Map<String, Object> formattedResult = new HashMap<>();
            if (originalResult != null && originalResult.containsKey("收盘价")) {
                formattedResult.put("closePrice", originalResult.get("收盘价"));
            } else {
                formattedResult.put("closePrice", 0.0);
            }
            
            // 缓存数据，设置30分钟过期，添加异常处理
            try {
                redisCache.setCacheObject(cacheKey, formattedResult, 30, java.util.concurrent.TimeUnit.MINUTES);
            } catch (Exception e) {
                // Redis异常时，忽略缓存
                System.err.println("Redis缓存写入异常: " + e.getMessage());
            }
            
            return ApiResponse.success("获取实时行情成功", formattedResult);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取实时行情失败: " + e.getMessage());
        }
    }
    
    /**
     * 判断是否应该使用缓存
     * 周六周日，或者时间在9:00之前或15:00之后使用缓存
     */
    private boolean shouldUseCache() {
        LocalDateTime now = LocalDateTime.now();
        int dayOfWeek = now.getDayOfWeek().getValue();
        LocalTime currentTime = now.toLocalTime();
        
        // 周六(6)或周日(7)
        boolean isWeekend = (dayOfWeek == 6 || dayOfWeek == 7);
        
        // 9:00之前或15:00之后
        LocalTime marketOpen = LocalTime.of(9, 0);
        LocalTime marketClose = LocalTime.of(15, 0);
        boolean isOffHours = currentTime.isBefore(marketOpen) || currentTime.isAfter(marketClose);
        
        // 检查Redis连接状态，如果连接不上也返回true
        boolean isRedisConnected = checkRedisConnection();
        
        return isWeekend || isOffHours || !isRedisConnected;
    }
    
    /**
     * 检查Redis连接状态
     * @return true-连接正常，false-连接异常
     */
    private boolean checkRedisConnection() {
        try {
            // 尝试执行一个简单的Redis命令来检查连接
            redisCache.getCacheObject("test:connection");
            return true;
        } catch (Exception e) {
            // Redis连接异常
            System.err.println("Redis连接检查失败: " + e.getMessage());
            return false;
        }
    }
}